/****************************************************************
 ** Product  :   HP Subscriber Network Application Policy
 ** Module   :   gr-manager
 ** Date: Apr 10, 2015               
 ** Author: Chen Zhenhua
 ** (C) Copyright 2015, Hewlett-Packard Company, All Rights Reserved.
 ** This software is the proprietary information of HP, Inc.  
 ** Use is subject to license terms.
 *****************************************************************
 ** Description:   
 **  Register a Linux cron job for the GR tool with the specific cron expression.
 **  
 ****************************************************************/
package com.hp.snap.gr.action.impl;

import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.jaxb.ActionType;
import com.hp.snap.gr.model.jaxb.GeneralActionType;
import com.hp.snap.gr.model.jaxb.ParameterType;
import com.hp.snap.gr.utils.CmdResult;
import com.hp.snap.gr.utils.CmdUtils;
import com.hp.snap.gr.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

/**
 * Register a Linux cron job for the GR tool with the specific cron expression. 
 * The existing cron job will remain in the new cron job list.
 *
 * There are two parameters configured in the action: Command and Schedule.
 * Command:GR Tool command.
 * Schedule: Cron expression;
 * 
 * <P>
 * Version: 3.3 <br>
 * Author: Chen Zhenhua
 * Date: Apr 10, 2015
 * 
 * </P>
 *
 **/
public class RegisterCronjobActionHandler extends AbstractActionHandler {

    private static Logger logger = LoggerFactory.getLogger(RegisterCronjobActionHandler.class);


    @Override
    public void execute(ActionType action,
                        Map<String, Object> actionPlanInputs,
                        Map<String, Object> actionPlanOutputs) throws ActionException {

        GeneralActionType actionType = (GeneralActionType) action;
        List<ParameterType> parameterTypes = actionType.getParameter();
        Map<String, String> parameterMap = Utils.contructParamMap(parameterTypes);
        String schedule = parameterMap.get("Schedule");
        String command = Utils.getConfigurationValue("USER_GR_BIN") + "/" + parameterMap.get("Command");
        String shellCommand = "";
        try {
            CmdResult result = new CmdResult();
            int rs = CmdUtils.runShellScript("crontab -l", result);
            if (rs == 0) {
                String cronJobs = result.getStdout().toString();
                LineNumberReader r = new LineNumberReader(new StringReader(cronJobs));
                for (String line = r.readLine(); line != null; line = r.readLine()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("exist cron job:{}", line);
                    }
                    if (line.endsWith(command)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("The command:{} existed in the cron job list", command);
                        }
                        return;
                    }
                }
                shellCommand = "crontab -l >> cron.job && echo \"" + schedule + " " + command + "\">>cron.job && crontab cron.job && rm -rf cron.job ";
            } else if (rs == 1) {
                //logger.warn("Do not found cron job exist");
                shellCommand = "echo \"" + schedule + " " + command + "\">>cron.job && crontab cron.job && rm -rf cron.job ";
            }
        } catch (Exception e) {
            logger.error("hander the register cron job error, the exception is:{}", e.getMessage());
            throw new ActionException("hander the register cron job error", e.getCause());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("register cron job shell command is {}", shellCommand);
        }
        try {
            CmdResult result = new CmdResult();
            int rs = CmdUtils.runShellScript(shellCommand, result);
            if (rs != 0) {
                logger.error("register the cron job failed, command is {}, schedule is:{} ", new Object[]{command, schedule});
                throw new ActionException("register cron job failed!!");
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new ActionException("register cron job failed!!", ex.getCause());
        }


    }

}
